package com.cevent.template.prod.util;

import ch.qos.logback.classic.db.names.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.plaf.nimbus.State;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cevent
 * @create 2025/3/12 0:43
 * 数据库配置
 */
public class ConnectionSet {

    public static final Logger LOG= LoggerFactory.getLogger(ConnectionSet.class);

    // 数据库连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // 本地测试环境
            String url = "jdbc:mysql://192.168.1.4:3306/cms_shop";
            String user = "cevent";
            String password = "cevent";
            connection = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }

        return connection;
    }

    // 获取表注释
    public static String getTableComment(String tableName) {
        Connection connection=getConnection();
        String tableNameCN="";
        try {
            Statement statement=connection.createStatement();
            //查询表注释，获取结果集
            ResultSet resultSet=statement.executeQuery("SELECT table_comment from information_schema.TABLES where TABLE_NAME='"+ tableName+"'");
            if(resultSet!=null){
                while(resultSet.next()){
                    tableNameCN=resultSet.getString("table_comment");
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        LOG.info("生成表中-----获取表名注释：{}",tableNameCN);
        return tableNameCN;
    }

    //获取列信息
    public static List<FieldSet> getColumnInfo(String tablenName){
        List<FieldSet> fieldSetList=new ArrayList<>();
        Connection connection=getConnection();
        try {
            Statement statement=connection.createStatement();
            ResultSet resultSet=statement.executeQuery("SHOW FULL COLUMNS FROM "+tablenName);
            if(resultSet!=null){
                while(resultSet.next()){
                    String columnName=resultSet.getString("Field");
                    String type=resultSet.getString("Type");
                    String comment=resultSet.getString("Comment");
                    String nullAble=resultSet.getString("Null");


                    FieldSet fieldSet=new FieldSet();
                    fieldSet.setName(columnName);
                    fieldSet.setType(type);
                    fieldSet.setComment(comment);
                    //是否为空判断，equals返回true或false
                    fieldSet.setNullEnable("YES".equals(nullAble));
                    fieldSet.setNameSmallHump(DataSet.underLineToSmallHump(columnName));
                    fieldSet.setNameBigHump(DataSet.underLineToBigHump(columnName));
                    fieldSet.setTypeJava(DataSet.sqlTypeToJavaType(type));
                    if(comment.contains("|")){
                        fieldSet.setNameCn(comment.substring(0,comment.indexOf("|")));
                    }else{
                        fieldSet.setNameCn(comment);
                    }
                    //char类型一般为固定长度，如uuid或者枚举字段（前端为下拉/选择无需校验）,longtext等设有最大值，但一般够不着，这里不做校验
                    if(type.toLowerCase().contains("varchar")){
                        //判断大于0需要校验
                        String lengthStr=type.substring(type.indexOf("(")+1,type.length()-1);
                        fieldSet.setLength(Integer.valueOf(lengthStr));
                    }else{
                        //如果不是varchar不需要校验，默认长度为0
                        fieldSet.setLength(0);
                    }

                    /** 判断comment是否有枚举
                     * `type_id` int(11) NOT NULL DEFAULT '0' COMMENT
                     * '模块类型|枚举[ModuleTypeEnum]:
                     * BASE_MODULE(0,"基础模块"),
                     * ARTICLE_MODULE(1,"文章模块"),
                     * PRODUCT_MODULE(2,"产品模块"),
                     * STATIC_MODULE(3,"静态模块"),
                     * REDIRECT_MODULE(4,"转向链接"),
                     * GUESTBOOK_MODULE(5,"客户留言")等
                     **/

                    if(comment.contains("枚举")){
                        fieldSet.setEnum(true);
                        int start=comment.indexOf("[");
                        int end=comment.indexOf("]");
                        String enumName=comment.substring(start+1,end);
                        //将enumName转为ENUM_NAME下划线分割
                        String enumConst=DataSet.getEnumToUnderLine(enumName);
                    }

                    fieldSetList.add(fieldSet);
                }

            }

            resultSet.close();
            statement.close();
            connection.close();
            LOG.info("生成枚举LIST：{}",fieldSetList);
            return fieldSetList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
